<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\roleRequest;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Http\Request;
use Auth;

class RolesController extends Controller
{
    public function index()
    {
        return Role::get();
    }

    public function store(RoleRequest $request)
    {
        $role = Role::create($request->only('name', 'description', 'status'));
        return $role;
    }

    public function edit(Role $role)
    {
        return $role;
    }

    public function update(roleRequest $request, Role $role)
    {
        $role->update($request->only('name', 'description', 'status'));
        return $role;
    }

    public function destroy(Role $role)
    {
        $role->delete();

        // 关联用户、权限
        $role->users()->detach();
        $role->permissions()->detach();
    }

    /**
     * 分配权限
     *
     * @param Request $request
     * @param Role $role
     * @return array
     */
    public function givePermission(Request $request, Role $role)
    {
        if ($request->isMethod('post')){
            return $role->permissions()->sync($request->permissions);
        }
        return [
            'permissions' => Permission::get(['id', 'name', 'title', 'pid']),
            'myPermissions' => $role->permissions()->get()->pluck('id'),
        ];
    }




}